'''
Author: @zhyy
Date: 2021-02-07 17:09:25
LastEditors: @zhyy
LastEditTime: 2021-02-09 16:18:33
'''
# coding:utf-8
import time,sys,os,uuid,json,re
from app import db
from flask import request, jsonify,current_app,g
from app.models.model import User
from app.func import error_code as RET
from app.validators.token import generate_token
from app.cache.redis_cache import db_cache,token_cache,uname_cache
from app.dao.user import UserDB



# 创建管理员
def create_admin():
    user = User(
        name="admin123",
        password="123456",
        addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    try:
        db.session.add(user)
        db.session.commit()
    except:
        print("创建用户失败")
    return jsonify({'code': 200, 'msg': "注册成功"})



def admin_login():
    req_data=request.get_json()
    admin_name=req_data.get("admin_name")
    password=req_data.get("password")
    if not all([admin_name,password]):
        current_app.logger.error(RET.PARAMERR.msg)
        return jsonify(code=RET.PARAMERR.code,msg=RET.PARAMERR.msg)
    filters={
        User.name==admin_name
    }
    user=UserDB.get_one(filters)
    if user:
        user_id=user.get("id")
        scope=user.get("scope")
        token = generate_token(user_id, scope)
        expiration=current_app.config["TOKEN_EXPIRATION"]
        name=current_app.config["REDIS_PREFIX"]+str(user.id)+"_"+str(uuid)
        token_cache=token_cache.set_token(token=token,token_name=name,expiration=expiration)
        if token_cache:
            return jsonify(RET.Success.json_msg(data=token))
        else:
            return jsonify(RET.LoginFailed.json_msg())



#--------------------------用户信息----------------------------------------
def get_user_info():
    filters={
        User.id==g.user_id
    }
    user=UserDB.get_one(filters)
    if user:
        return jsonify(RET.Success.json_msg(data=user))

# 注销登录
def logout():
    user_id = g.user_id
    uuid = g.uuid
    name = current_app.config["REDIS_PREFIX"] + str(user_id) + "_" + str(uuid)
    token_cache.del_token(name)
    return jsonify(code=RET.OK,data="success",message="注销成功")

